package com.shiguiwu.springmybatis.javabase.thread.lock.impl;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @description: 为锁续命线程
 * @author: stone
 * @date: Created by 2022/1/15 21:16
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.lock.impl
 */
@EqualsAndHashCode(callSuper = true)
@Data
@Slf4j
@NoArgsConstructor
public class AddTimeForLock extends Thread {

    //锁的key
    private String lockKey;

    //锁的value
    private String uuid;

    //redis
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 设置线程睡眠时间为5s
     */
    private static final long SLEEP_TIME = 5000;

    /**
     * 设置锁的过期时间为10s
     */
    private static final long EXPIRE_Time = 10;






    public AddTimeForLock(String lockKey, String uuid,RedisTemplate<String, String> redisTemplate){
        this.lockKey = lockKey;
        this.uuid = uuid;
        this.redisTemplate = redisTemplate;
    }


    @Override
    public void run() {
        while (true) {
            String value = redisTemplate.opsForValue().get(lockKey);
            if (uuid.equalsIgnoreCase(value)) {
                //如果该锁还没有被释放，则将过期时间往后推10s 原则是 过期时间/3
                redisTemplate.expire(lockKey, EXPIRE_Time, TimeUnit.SECONDS);

                //每个5s检查一次锁
                try {
                    TimeUnit.SECONDS.sleep(SLEEP_TIME);
                } catch (InterruptedException e) {
                    log.error("thread sleep err.......");
                    e.printStackTrace();
                }

            }
            else {
                return;
            }
        }
    }
}
